package com.lgy.controller;

import com.alibaba.fastjson.JSONObject;
import com.lgy.vo.ResultVO;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class BaseController {

    public static final String ERROR_PAGE = "common/error";

    public static final String REDIRECT = "redirect:";
    public static final String FORWARD = "forward:";

    public ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    public HttpServletResponse getHttpServletResponse() {
        return getServletRequestAttributes().getResponse();
    }

    public HttpSession getHttpSession() {
        return getHttpServletRequest().getSession();
    }

    // 请求头
    public String getHeader(String name) {
        return getHttpServletRequest().getHeader(name);
    }

    // 请求URI
    public String getRequestURI() {
        return getHttpServletRequest().getRequestURI();
    }

    // 成功返回
    public ResultVO success() {
        return success(null, null);
    }

    public ResultVO success(String message, Object data) {
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(0);
        resultVO.setMessage(StringUtils.isEmpty(message) ? "成功" : message);
        resultVO.setData(data);
        return resultVO;
    }

    // 错误返回
    public ResultVO fail(Integer code, String message) {
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(code);
        resultVO.setMessage(StringUtils.isEmpty(message) ? "失败" : message);
        resultVO.setData(null);
        return resultVO;
    }

    // 信息返回给前端
    public void returnMsg(Integer code, String msg) {
        HttpServletResponse response = getHttpServletResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(JSONObject.toJSONString(fail(code, msg)).getBytes());
            IOUtils.closeQuietly(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
